package com.ruoyi.web.core.config;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.config.mq.AESBase64Utils;
import com.ruoyi.common.config.mq.MessageData;
import com.ruoyi.common.config.mq.MessageVO;
import com.ruoyi.common.config.mq.MqConfigs;
import com.ruoyi.common.config.mq.MqConsumer;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeviceDataService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author chmj
 * @version V1.0
 * @Package com.ruoyi.common.config
 * @Copyright 2022/3/17 13:12 汇博医疗股份有限公司
 */
//@Configuration
public class TuyaConfig {

    @Autowired
    private ISysDeviceDataService deviceDataService;

    @Bean
    public void threadTuya() throws Exception {

        Thread mqThread = new Thread() {
            @SneakyThrows
            @Override
            public void run() {
                String url = MqConfigs.CN_SERVER_URL;
                String accessId = "3y8s3pneb94vug2s2fqx";
                String accessKey = "bc9f00bebdd74b878db0e9b069bac9f7";
                MqConsumer mqConsumer = MqConsumer.build().serviceUrl(url).accessId(accessId).accessKey(accessKey).maxRedeliverCount(3).messageListener(message -> {
                    System.out.println("---------------------------------------------------");
                    System.out.println("Message received:" + new String(message.getData()) + ",seq="
                            + message.getSequenceId() + ",time=" + message.getPublishTime() + ",consumed time="
                            + System.currentTimeMillis());
                    String jsonMessage = new String(message.getData());
                    MessageVO vo = JSON.parseObject(jsonMessage, MessageVO.class);
                    System.out.println("the real messageVO data:" + AESBase64Utils.decrypt(vo.getData(), accessKey.substring(8, 24)));
                    MessageData mData = JSON.parseObject(AESBase64Utils.decrypt(vo.getData(), accessKey.substring(8, 24)), MessageData.class);
                    if (StringUtils.isNotNull(mData.getStatus()) && mData.getStatus().size() != 0) {
                        System.out.println("the real message data:" + JSON.toJSONString(mData.getStatus()));
                        deviceDataService.saveData(mData.getDevId(), mData.getStatus().get(0));
                    }
                });
                mqConsumer.start();
            }
        };
        mqThread.start();
    }
}
